# -*- Mode: Python -*- vi:si:et:sw=4:sts=4:ts=4:syntax=python
from cerbero.errors import FatalError
from cerbero.utils import shell
from cerbero.utils import messages as m
import shutil

class Recipe(recipe.Recipe):
    name = 'libvpx'
    version = 'v1.6.0'
    licenses = [License.BSD]
    btype = BuildType.MAKEFILE
    remotes = {'origin': 'https://github.com/webmproject/libvpx.git'}
    commit = 'v1.6.0'
    configure_tpl = "./configure --prefix=%(prefix)s "\
                    "--libdir=%(libdir)s %(options)s"
    configure_options = "--enable-pic --as=yasm --disable-unit-tests --size-limit=16384x16384 "\
                        "--enable-postproc --enable-multi-res-encoding --enable-temporal-denoising "\
                        "--enable-vp9-temporal-denoising --enable-vp9-postproc "
    add_host_build_target = False
    supports_cache_variables = False
    can_use_configure_cache = False
    make = 'make HAVE_GNU_STRIP=no'

    patches = ['libvpx/0001-build-Fix-the-min-version-flag-for-iOS-simulator-bui.patch',
               'libvpx/0002-Include-Android-cpu-features.c-instead-of-.h.patch',
               'libvpx/0003-configure-Add-back-the-armv5te-android-gcc-target.patch',
               'libvpx/0004-build-Remove-broken-custom-android-toolchain-usage.patch',
               'libvpx/0005-configure-Add-Android-ARM64-support.patch',
               'libvpx/0006-Don-t-embed-bitcode-on-iOS-until-we-support-that-pro.patch',
               ]

    files_libs = ['libvpx']
    files_bins = ['vpxenc', 'vpxdec']
    files_devel = ['include/vpx', 'lib/pkgconfig/vpx.pc']

    # libvpx does not have check target
    make_check = None


    def prepare (self):
        if self.config.target_arch == Architecture.X86_64:
            arch = 'x86_64'
        elif self.config.target_arch == Architecture.X86:
            arch = 'x86'
        elif self.config.target_arch == Architecture.ARM:
            arch = 'arm'
        elif self.config.target_arch == Architecture.ARMv7:
            arch = 'armv7'
        elif self.config.target_arch == Architecture.ARMv7S:
            arch = 'armv7s'
        elif self.config.target_arch == Architecture.ARM64:
            arch = 'arm64'

        self.new_env['LD'] = os.environ.get('CC', 'gcc')
        if self.config.target_platform == Platform.DARWIN:
            platform = 'darwin12'
        elif self.config.target_platform == Platform.IOS:
            if self.config.target_arch == Architecture.X86 or self.config.target_arch == Architecture.X86_64:
                platform = 'iphonesimulator'
            else:
                platform = 'darwin'
            if self.config.target_arch == Architecture.ARM:
                arch = 'armv6'
        elif self.config.target_platform == Platform.WINDOWS:
            if self.config.target_arch == Architecture.X86_64:
                platform = 'win64'
            else:
                platform = 'win32'
                self.append_env['CFLAGS'] = " -mstackrealign "
        # FIXME:
        elif self.config.target_platform == Platform.ANDROID:
            platform = 'android'
            self.append_env['CFLAGS'] = " -Dandroid_getCpuFamily=vpx_android_getCpuFamily "\
                "-Dandroid_getCpuFeatures=vpx_android_getCpuFeatures "\
                "-Dandroid_getCpuCount=vpx_android_getCpuCount " \
                "-Dandroid_cpuInit=vpx_android_cpuInit " \
                "-Dandroid_cpuInitDummy=vpx_android_cpuInitDummy " \
                "-Dandroid_getCpuIdArm=vpx_android_getCpuIdArm " \
                "-Dandroid_setCpu=vpx_android_setCpu " \
                "-Dandroid_setCpuArm=vpx_android_setCpuArm "

            if self.config.target_arch == Architecture.X86:
                self.append_env['ASFLAGS'] = " -D__ANDROID__ "
                self.append_env['CFLAGS'] += " -D__ANDROID__ "

            if self.config.target_arch == Architecture.ARM:
                arch = 'armv5te'
                # Fix compiler error with -mthumb
                self.new_env['CFLAGS'] = os.environ['CFLAGS'].replace('-mthumb', '')
            elif self.config.target_arch in [Architecture.ARMv7, Architecture.X86, Architecture.ARM64, Architecture.X86_64]:
                pass
            else:
                raise FatalError("Unsupported Android architecture %s" % self.config.target_arch)
            self.config_sh = 'LD=$CC ./configure'
            self.configure_options.replace('--as=yasm', '')
            self.configure_options += ' --sdk-path=%s ' % self.config.toolchain_prefix
        else:
            self.configure_options += '--enable-shared '
            platform = 'linux'

        self.configure_options += ' --disable-examples '

        self.configure_options += '--target=%s-%s-gcc ' % (arch, platform)

        # Optimize for real-time performance
        self.configure_options += ' --enable-realtime-only --enable-onthefly-bitpacking '

        # Enable error concealment
        self.configure_options += ' --enable-error-concealment '

    def configure(self):
        if self.config.target_platform == Platform.ANDROID:
            cpufeatures_path = os.path.join(self.config.toolchain_prefix, 'sources', 'android', 'cpufeatures')
            o = os.path.join(cpufeatures_path, 'cpu-features.h')
            f = os.path.join(self.make_dir, 'vpx_ports')
            m.action("copying %s to %s" % (o, f))
            shutil.copy(o, f)
            f = self.make_dir
            m.action("copying %s to %s" % (o, f))
            shutil.copy(o, f)
            o = os.path.join(cpufeatures_path, 'cpu-features.c')
            f = os.path.join(self.make_dir, 'vpx_ports')
            m.action("copying %s to %s" % (o, f))
            shutil.copy(o, f)
        super(recipe.Recipe, self).configure()

    def install(self):
        if self.config.target_platform in [Platform.DARWIN, Platform.IOS]:
            for f in ['vpxenc', 'vpxdec', 'libvpx.a']:
                shell.touch(os.path.join(self.build_dir, f))
        super(Recipe, self).install()
